// import 'package:'
import 'package:flutter/material.dart';
import 'package:safety_platform/models/task.dart';
import 'package:safety_platform/bloc/task/task.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:safety_platform/components/button.dart';
import 'package:safety_platform/components/loading.dart';
import 'package:safety_platform/components/task_detail.dart';
import 'package:fluttertoast/fluttertoast.dart';

class TaskDetailPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _TaskDetailPageState();
  }

  final TaskDetailState initalState;

  const TaskDetailPage(this.initalState);
}

class _TaskDetailPageState extends State<TaskDetailPage> {
  TaskBloc _taskBloc;
  @override
  void initState() {
    super.initState();
    _taskBloc = TaskBloc(inital: widget.initalState);
    if (widget.initalState.task.items == null) {
      _taskBloc.dispatch(GetTaskItemsEvent(widget.initalState.task.id));
    }
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      child: BlocBuilder(
        bloc: _taskBloc,
        builder: (BuildContext context, TaskDetailState state) => _body(state),
      ),
      bloc: _taskBloc,
    );
  }

  Widget _bootomNavigationBar(TaskDetailState state) {
    // if (_task != null && _task.status == 'pending') {

    if (state.task.status != 'pending') {
      return Container(
        width: 0,
        height: 0,
      );
    }
    return Container(
        width: MediaQuery.of(context).size.width,
        height: 48,
        color: Colors.white,
        child: Button(
          //  loading: committing,
          buttonColor: Colors.white,
          onPressed: () {
            _submit(state);
          },
          text: '提交任务',
          textSize: 18,
          textColor: Color.fromARGB(255, 27, 130, 210),
        ));
    // }
    return null;
  }

  Widget _realBody() {}

  Future<bool> _onWillPop() {
    Navigator.of(context).pop();
    return Future.value(true);
  }

  Widget _body(TaskDetailState state) {
    Widget body;
    if (state is TaskDetailState) {
      if (state.task.items == null) {
        body = Loading();
      } else {
        body = TaskDetailWidget(state.task);
      }
    }
    return Scaffold(
      appBar: AppBar(
        // leading: appLeading(context),
        title: Text(state.task.name ?? '检查任务'),
        elevation: 0,
        backgroundColor: Color.fromARGB(255, 27, 130, 210),
        centerTitle: true, //设置标题是否局中
      ),
      backgroundColor: Color.fromARGB(255, 235, 235, 235),
      body: WillPopScope(child: body, onWillPop: () => _onWillPop()),
      bottomNavigationBar: _bootomNavigationBar(state),
    );
  }

  _submit(TaskDetailState state) {
    Task _task = state.task;
    List<TaskItem> items = _task.items;

    if (items.any((item) => item.result == null || item.result.length <= 0)) {
      Fluttertoast.showToast(msg: '还有项目未完成,请完成后提交');
      return;
    }

    _taskBloc.dispatch(SubmitTaskEvent(_task));
    // setState(() {
    //       committing = true;
    //     });
    // bool hasDanger = items.any((item) => item.result != item.rightAnswer);
    // if (!hasDanger) {
    //   //无风险，
    //   _task.status = 'done';
    // } else {
    //   _task.status = 'risky';
    // }
    // submitTask(_task).then((task) {
    //   Fluttertoast.showToast(msg: '任务提交成功');
    //   setState(() {
    //           committing = false;
    //         });
    //   Navigator.of(context).pushReplacement(
    //       MaterialPageRoute(builder: (_) => TaskResultPage(task)));

    // }).catchError((e) {
    //   setState(() {
    //           committing = false;
    //         });
    //   Fluttertoast.showToast(msg: '提交任务错误:$e');
    // });
  }
}
/*import 'package:safety_platform/utils.dart';
import 'package:safety_platform/models/task.dart';
import 'package:safety_platform/models/task_item.dart';
import 'package:safety_platform/pages/task/services.dart';
import 'package:safety_platform/components/loading.dart';
import 'package:safety_platform/iconfont.dart';
import 'dart:io';
import 'package:safety_platform/models/attachment.dart';
import 'package:safety_platform/pages/services.dart' as gs;
import 'package:image_picker/image_picker.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:safety_platform/pages/task/task_result.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
// import 'package:flutter_cached_network_image/c';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:safety_platform/components/button.dart';

class TaskDetailPage extends StatefulWidget {
  @override
  _TaskDetailState createState() => new _TaskDetailState();

  // TaskDetailPage({Key key, this.task});
  TaskDetailPage(this.task);
  final Task task;
  // Risk risk;
}

class _TaskDetailState extends State<TaskDetailPage> {
  Task _task;

  bool committing = false;
  @override
  Widget build(BuildContext context) {
    _task = widget.task;
    Widget body;
    if (_task.items == null || _task.items.length <= 0) {
      print('重新拉取任务信息');
      body = Loading();
      getTaskDetail(widget.task.id).then((Task task) {
        if (this.mounted) {
          setState(() {
            _task = task;
          });
        }
      });
    } else {
      print('开始任务1');
      body = _body(context);
    }

    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        // leading: appLeading(context),
        title: Text('检查任务'),
        elevation: 0,
        backgroundColor: Color.fromARGB(255, 27, 130, 210),
        centerTitle: true, //设置标题是否局中
      ),
      body: WillPopScope(child: body, onWillPop: () => _onWillPop()),
      bottomNavigationBar: _bootomNavigationBar(),
    );
  }

  Widget _bootomNavigationBar() {
    // if (_task != null && _task.status == 'pending') {
    return Container(
      width: MediaQuery.of(context).size.width,
      height: 48,
      color: Colors.white,
       child: Button(
         loading: committing,
              buttonColor: Colors.white,
              onPressed: () {
                _submit();
              },
              text: '提交任务',
              textSize: 18,
              textColor: Color.fromARGB(255, 27, 130, 210),
            )
      // child: RaisedButton(
      //   color: Colors.white,
      //   onPressed: () {
      //     print('提交任务');
      //     _submit();
      //   },
      //   child: Text(
      //     '提交',
      //     style: TextStyle(
      //       color: Color.fromARGB(255, 27, 130, 210),
      //       fontSize: 18,
      //     ),
      //   ),
      // ),
    );
    // }
    return null;
  }

  Future<bool> _onWillPop() {
    print('onWillPop ${this._task.status}');

    if (this._task.status != 'pending') {
      return Future<bool>.value(true);
    }
    return showDialog(
          context: context,
          barrierDismissible: false,
          builder: (context) => new AlertDialog(
                title: new Text('请确认'),
                content: new Text('任务还未完成，是否保存后退出'),
                actions: <Widget>[
                  new FlatButton(
                    onPressed: () => Navigator.of(context).pop(true),
                    child: new Text('否'),
                  ),
                  new FlatButton(
                    onPressed: () {
                      saveCache(_task);
                      Navigator.of(context).pop(true);
                    },
                    child: new Text('是'),
                  ),
                ],
              ),
        ) ??
        false;
  }

  

  _buildContext(int index) {
    TaskItem item = _task.items[index];
    _badget() {
      final Color rightAnswerColor = Color.fromARGB(255, 58, 116, 214);
      final Color negtiveAnswerColor = Color.fromARGB(255, 230, 140, 38);

      if (item.result != null) {
        var color = item.result == item.rightAnswer
            ? rightAnswerColor
            : negtiveAnswerColor;
        return Container(
          // margin: EdgeInsets.only(top: 10),
          padding: EdgeInsets.fromLTRB(6, 10, 6, 10),
          decoration: BoxDecoration(
            color: color,
          ),
          child: Text(
            item.result,
            style: TextStyle(
              color: Colors.white,
            ),
          ),
        );
      } else {
        return Container(
          width: 24,
        );
      }
    }

    return Container(
      // height: 60,
      decoration: BoxDecoration(
          // color:Colors.red,

          border: Border(
              bottom: BorderSide(
        color: Color.fromARGB(251, 241, 241, 241),
        width: 1,
      ))),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Padding(
            padding: EdgeInsets.all(8),
            child: SizedBox(
              height: 40,
              // width: 40,
              child: Column(
                children: <Widget>[
                  Text(
                    (index + 1).toString(),
                    style: TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ],
              ),
            ),
          ),
          Expanded(
            child: Container(
              padding: EdgeInsets.all(12),
              child: Text('${_task.items[index].content}'),
            ),
          ),
          _badget(),
        ],
      ),
    );
  }

  _buildAnswers(TaskItem taskItem, List<String> answers) {
    List<Widget> widgets = List();
    for (String answer in answers) {
      widgets.add(
        Expanded(
          child: GestureDetector(
            onTap: () {
              print('选择答案：$answer');
              setState(() {
                taskItem.result = answer;
              });
            },
            child: Container(
              height: 40,
              decoration: BoxDecoration(
                // color: Colors.yellow,
                border: Border(
                  right: BorderSide(
                    color: Color.fromARGB(255, 241, 241, 241),
                    width: 1,
                  ),
                ),
              ),
              // child: Expanded(
              child: Padding(
                padding: EdgeInsets.all(10),
                child: Center(
                  child: Text(answer),
                  // child: Icon(
                  //   MyIconFont.dingdan,
                  //   color: Colors.grey,
                  //   size: 24,
                ),
              ),
            ),
          ),
        ), // ),
      );
    }
    return widgets;
  }

  Function _onRemark(TaskItem item) {
    return () {
      if (item.showRemark == null) {
        item.showRemark = false;
      }
      setState(() {
        item.showRemark = !item.showRemark;
      });
    };
  }

  _submitRemark(TaskItem item, String value) {
    print('填写备注 => ${value}');
    item.remark = value;
  }

  _updateImage(TaskItem item, Attachment attachment, dynamic image) {
    gs
        .uploadPicture(image, attachment.screenName, prefix: 'taskitem')
        .then((uploadAttachment) {
      print('图片上传完成 【$uploadAttachment.url}】');
      attachment.id = uploadAttachment.id;
      attachment.uploadStatus = 'done';
      attachment.url = uploadAttachment.url;
      setState(() {});
    });
  }

  GestureTapCallback _onCamera(TaskItem item) {
    return () {
      int length = item.attachments.length;

      if (length >= 3) {
        Fluttertoast.showToast(msg: '每个项目最多上传三张图片');
        return;
      }
      print('当前item有${item.attachments.length}个附件');
      ImagePicker.pickImage(source: ImageSource.camera).then((image) {
        print(image);
        if (image != null) {
          Attachment attachment = Attachment(null, null, image.path, 'pending',
              'taskitem-${item.id}-${item.attachments.length + 1}.jpg');

          setState(() {
            item.attachments.add(attachment);
          });
          _updateImage(item, attachment, image);
        }

        // gs.uploadPicture(image, 'taskitem-${item.id}-${item.attachments.length+1}.jpg')
      });
    };
  }

  List<Widget> _buildIconAction(TaskItem item) {
    Widget _iconAction(IconData data, Function cb) {
      return Expanded(
        child: GestureDetector(
          onTap: () {
            cb();
          },
          child: Container(
            height: 40,
            decoration: BoxDecoration(
              border: Border(
                right: BorderSide(
                  width: 1,
                  color: Color.fromARGB(255, 241, 241, 241),
                ),
              ),
            ),
            child: Padding(
                padding: EdgeInsets.all(8),
                child: Center(
                    child: Icon(
                  data,
                  size: 24,
                  color: Colors.grey,
                ))),
          ),
        ),
      );
    }

    List<Widget> widgets = List();
    widgets.add(_iconAction(MyIconFont.xiangji, _onCamera(item)));
    widgets.add(_iconAction(MyIconFont.dingdan, _onRemark(item)));

    widgets.add(
      GestureDetector(
        onTap: () {
          setState(() {
            item.attachments = [];
            item.result = null;
            item.remark = null;
          });
        },
        child: Container(
          width: 100,
          child: Padding(
            padding: EdgeInsets.fromLTRB(16, 8, 16, 8),
            child: Center(
              child: Icon(MyIconFont.lajitong, color: Colors.grey, size: 24),
            ),
          ),
        ),
      ),
    );
    return widgets;
  }

  Widget _buildAttachments(TaskItem item) {
    if (item.attachments != null && item.attachments.length > 0) {
      List<Widget> children = item.attachments.map<Widget>((attachment) {
        Widget child;
        print('attachment =>$attachment');
        if (attachment.localPath != null) {
          child = Image.file(File(attachment.localPath),
              fit: BoxFit.fill, width: 80, height: 80);
        } else {
          if (attachment.url != null) {
            child = CachedNetworkImage(
              imageUrl: attachment.url,
              placeholder: Center(
                child: SpinKitCircle(size:50, color: Theme.of(context).primaryColor),
              ),
              errorWidget: new Icon(Icons.error),
              fit: BoxFit.fill,
            );
          }
        }
        return Container(
            width: 80,
            height: 80,
            margin: EdgeInsets.fromLTRB(8, 4, 8, 4),
            child: child);
      }).toList();

      return Container(
        padding: EdgeInsets.all(4),
        decoration: BoxDecoration(
          color: Color.fromARGB(255, 246, 247, 250),
          border: Border(
            bottom: BorderSide(
              color: Color.fromARGB(255, 241, 241, 241),
              width: 1,
            ),
          ),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: children,
        ),
      );
    }
    return Container();
  }

  Widget _buildRemark(TaskItem item) {
    if (item.showRemark == null || !item.showRemark) {
      return Container();
    }
    return Container(
      margin: EdgeInsets.fromLTRB(0, 0, 0, 0),
      color: Color.fromARGB(255, 246, 247, 250),
      child: Container(
        color: Colors.white,
        margin: EdgeInsets.all(14),
        child: TextField(
          maxLines: 4,
          maxLength: 200,
          textInputAction: TextInputAction.send,
          onChanged: (value) => _submitRemark(item, value),
          decoration: InputDecoration(
              contentPadding: EdgeInsets.all(4),
              hintText: '请输入备注',
              border: InputBorder.none,
              hintStyle: TextStyle(
                fontSize: 14,
              )),
        ),
      ),
    );
  }

  _buildAction(TaskItem item) {
    List<String> answers = item.answers.split(',');

    List<Widget> answersWidget = List();

    if (item.result == null) {
      answersWidget = _buildAnswers(item, answers);
    } else {
      answersWidget = _buildIconAction(item);
    }
    // for (String answer in answers) {
    //   answersWidget.add(
    //     Expanded(
    //       child: Container(
    //         decoration: BoxDecoration(
    //           // color: Colors.yellow,
    //           border: Border(
    //             right: BorderSide(
    //               color: Color.fromARGB(255, 241, 241, 241),
    //               width: 1,
    //             ),
    //           ),
    //         ),
    //         // child: Expanded(
    //         child: Padding(
    //           padding: EdgeInsets.all(10),
    //           child: Center(
    //             //   child: Text(answer),
    //             child: Icon(
    //               MyIconFont.dingdan,
    //               color: Colors.grey,
    //               size: 24,
    //             ),
    //           ),
    //         ),
    //         // ),
    //       ),
    //     ),
    //   );
    // }
    // answersWidget.add(
    //   Container(
    //     child: Padding(
    //       padding: EdgeInsets.all(10),
    //       child: Center(
    //         child: Icon(MyIconFont.dingdan, color: Colors.grey, size: 24),
    //       ),
    //     ),
    //   ),
    // );
    return Container(
      // padding: EdgeInsets.fromLTRB(0, 8, 0, 8),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: answersWidget,
      ),
    );
  }

  _buildTaskItem(BuildContext context, int index) {
    TaskItem item = _task.items[index];
    return Container(
        // color: Colors.,
        child: Card(
          elevation: 0,
          color: Colors.white,
          child: Column(
            children: <Widget>[
              _buildContext(index),
              _buildAttachments(item),
              _buildRemark(item),
              _buildAction(item),
            ],
          ),
        ),
        margin: EdgeInsets.fromLTRB(8, 0, 8, 0));
  }

  Widget _body(BuildContext context) {
    print('共有任务项 ${_task.items.length}');
    return Container(
      padding: EdgeInsets.fromLTRB(0, 8, 0, 8),
      color: Color.fromARGB(255, 235, 235, 235),
      child: ListView.builder(
        itemCount: _task.items.length,
        itemBuilder: (BuildContext context, int index) =>
            _buildTaskItem(context, index),
      ),
    );
  }
}

*/
